package com.sky.course.controller;

import com.sky.course.entity.MessageForm;
import com.sky.course.service.CmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

@RestController
@RequestMapping(value = "/cms")
@Api(value = "短信验证工具",description = "短信验证工具")
public class CmsController {
    @Autowired
    private CmsService cmsService;

    @ApiOperation(value = "发送短信验证码",notes = "发送短信验证码")
    @RequestMapping(value = "/sendMessage",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Mobile", value = "手机号", dataType = "String", paramType = "query", required = true)
    })
    public boolean sendMessage(@RequestParam String Mobile, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String str = "";
        //随机生成6位的验证码
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str += random.nextInt(10);
        }
        MessageForm messageForm = new MessageForm();
        messageForm.setMobiles(Mobile);
        messageForm.setCaptcha(str);
        session.setAttribute(Mobile,str);
        //此处只进行时间判断5分钟，不做手机号发送次数限制
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                session.removeAttribute(Mobile);
                System.out.println("过期的验证码已经清理");
                timer.cancel();
            }
        },5 * 6 * 1000);
        return cmsService.sendMessage(messageForm);
    }

    @ApiOperation(value = "验证短信验证码",notes = "验证短信验证码")
    @RequestMapping(value = "/receive",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Mobile", value = "手机号", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "MobileMa", value = "短信验证码", dataType = "String", paramType = "query", required = true)
    })
    public boolean receive(String Mobile,String MobileMa,HttpServletRequest request){
        HttpSession session = request.getSession();
        String Ma = (String)session.getAttribute(Mobile);
        return Ma.equals(MobileMa);
    }
}
